package com.cgl.service.imp;

import com.cgl.mapper.LeaveMessageMapper;
import com.cgl.pojo.LeaveMessage;
import com.cgl.service.LeaveMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class LeaveMessageServiceImp implements LeaveMessageService {
    @Autowired
    private LeaveMessageMapper leaveMessageMapper;
    @Override
    public int addLeaveMessage(LeaveMessage leaveMessage) {
        leaveMessage.setStatus("1");
        leaveMessage.setCreatedTime(LocalDateTime.now());

        return leaveMessageMapper.addLeaveMessage(leaveMessage);
    }

    @Override
    public List<LeaveMessage> getAllLeaveMessage() {
        int allCount = leaveMessageMapper.getAllConunt();
        if (allCount<=12){
            return leaveMessageMapper.getAllLeaveMessage();
        }
        else {
            try {
                // 如果留言总数大于12，随机选择一个起始索引
                int start = new Random().nextInt(allCount - 12);
                // 返回从起始索引开始的12条留言
                return leaveMessageMapper.getAllLeaveMessageByPage(start, 12);
            } catch (Exception e){
                return null;
            }
        }
    }

    @Override
    public int getAllConunt() {
        return leaveMessageMapper.getAllConunt();
    }
}
